﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.ComponentModel;
using System.Web;
using System.Collections.Specialized;
using System.Net;
using System.Timers;

namespace WasaWasa
{
    /// <summary>
    /// AuthenticationWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class AuthenticationWindow : Window
    {
        private const string _ = "nQlo5Mo7GyWVSOgNvBROz0USGmsYr3PR";
        private const string AppKey = "jyKhNlaT1hPPyRnJ1dREsfwCppAyntnE";
        private const string CallbackHost = "hcm.wankuma.com";
        private const string CallbackPath = "/wasawasa/auth.htm";

        private static readonly DependencyPropertyKey AuthenticationTokenPropertyKey =
            DependencyProperty.RegisterReadOnly("AuthenticationToken", typeof(string), typeof(AuthenticationWindow), new PropertyMetadata(null));
        public static readonly DependencyProperty AuthenticationTokenProperty =
            AuthenticationTokenPropertyKey.DependencyProperty;

        public string AuthenticationToken
        {
            get { return GetValue(AuthenticationTokenProperty) as string; }
            private set { SetValue(AuthenticationTokenPropertyKey, value); }
        }

        public AuthenticationWindow()
        {
            InitializeComponent();
            browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
            browser.Navigate(string.Format("http://wassr.jp/auth/?app_key={0}&sig={1}", AppKey, computeSig("app_key", AppKey)));
        }

        void browser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            Uri resuri = e.Url;
            if (resuri.Host == CallbackHost && resuri.AbsolutePath == CallbackPath)
            {
                NameValueCollection nvc = HttpUtility.ParseQueryString(resuri.Query);
                string token = nvc["token"];
                string hashhex = nvc["hmac"];

                if (hashhex == computeSig("token", token))
                {
                    this.AuthenticationToken = token;
                    DialogResult = true;
                    Close();
                }
            }
        }

        private string computeSig(string name, string value)
        {
            HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(_), true);
            byte[] hashbin = hmac.ComputeHash(Encoding.ASCII.GetBytes(name + value));
            string hashhex = BitConverter.ToString(hashbin).Replace("-", "").ToLower();
            return hashhex;
        }
    }
}
